package com.patmen.android.PhoneCard;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnDismissListener;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.View.OnTouchListener;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.TranslateAnimation;
import android.widget.AbsoluteLayout;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;

/**
 * This class defines the activity that is created when this program is started.
 * The preferences UI is created from here.
 * 
 * @author Arvind Menon
 * @author Amruta Patwardhan
 */
public class PhoneCard extends ListActivity {

	/**
	 * The preferences file to store PhoneCard preferences and profiles
	 * 
	 * @see http://code.google.com/p/phonecard/wiki/Design#Preferences_Format
	 */
	public static final String PREFS_NAME = "PhoneCardPreferences";

	// Menu item ids
	public static final int MENU_PROFILE_DELETE = Menu.FIRST;
	public static final int MENU_PROFILE_ADD = Menu.FIRST + 1;
	public static final int MENU_PHONECARD_ACTIVE = Menu.FIRST + 2;

	// Other constants
	public static final int ACTIVITY_EDIT_PROFILE = 10;
	public static final int ACTIVITY_CREATE_PROFILE = 11;

	// Preferences
	private SharedPreferences mSettings;
	private boolean mPhoneCardActive;
	private int mNumProfiles;

	/** Called when the activity is first created. */
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// Restore preferences
		mSettings = getSharedPreferences(PREFS_NAME, 0);
		mPhoneCardActive = mSettings.getBoolean("PhoneCardActive", false);
		mNumProfiles = mSettings.getInt("NumProfiles", 0);

		dispProfileList();

		// Add the listener for a long-press
		this.getListView().setOnItemLongClickListener(
				new OnItemLongClickListener() {
					public boolean onItemLongClick(AdapterView<?> arg0,
							View arg1, final int arg2, long arg3) {

						final Builder winAlert;
						Dialog winDialog;

						winAlert = new AlertDialog.Builder(arg1.getContext())
								.setIcon(R.drawable.icon).setTitle(
										"Delete Profile?").setCancelable(true)
								.setNegativeButton("No", null)
								.setPositiveButton("Yes",
										new DialogInterface.OnClickListener() {

											public void onClick(
													DialogInterface dialog,
													int which) {
												deleteProfile(arg2);
											}
										});
						winDialog = winAlert.create();
						winDialog.setCanceledOnTouchOutside(true);
						winDialog.show();

						return false;
					}
				});

		// Set Listener for list item selection
		this.getListView().setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				editProfile(arg2);
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);

		// This is our standard application actions
		// - add a new profile
		// - Enable/Disable PhoneCardProgram
		menu.add(0, MENU_PROFILE_ADD, 0, R.string.menu_profile_add)
				.setShortcut('3', 'a').setIcon(android.R.drawable.ic_menu_add);
		menu.add(
				0,
				MENU_PHONECARD_ACTIVE,
				0,
				mPhoneCardActive ? R.string.menu_phonecard_disable
						: R.string.menu_phonecard_enable).setShortcut('3', 'a')
				.setIcon(
						mPhoneCardActive ? android.R.drawable.ic_media_pause
								: android.R.drawable.ic_media_play);
		return true;

	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case MENU_PROFILE_ADD:
			// Launch activity to add a new profile
			editProfile(mNumProfiles);
			return true;
		case MENU_PHONECARD_ACTIVE:
			mPhoneCardActive = !mPhoneCardActive;
			item.setTitle(mPhoneCardActive ? R.string.menu_phonecard_disable
					: R.string.menu_phonecard_enable);
			item.setIcon(mPhoneCardActive ? android.R.drawable.ic_media_pause
					: android.R.drawable.ic_media_play);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	protected void onStop() {
		super.onStop();

		// Save user preferences.
		SharedPreferences.Editor editor = mSettings.edit();
		editor.putBoolean("PhoneCardActive", mPhoneCardActive);
		// Each Profile should be saved in the EditProfile Activity.
		// No need to save the profiles here
		editor.commit();
	}

	@Override
	protected void onResume() {
		super.onResume();
		mNumProfiles = mSettings.getInt("NumProfiles", 0);
		dispProfileList();
	}

	/**
	 * Function to edit or add a profile. The index refers to the index saved in
	 * the preferences file. If this is a new profile, index will be equal to
	 * numProfiles.
	 * 
	 * @param profileIndex
	 */
	private void editProfile(int profileIndex) {
		// Start the edit profile activity
		Intent intent = new Intent(this,
				com.patmen.android.PhoneCard.ProfileEditor.class);
		intent.putExtra("ProfileIndex", profileIndex);
		if(profileIndex == mNumProfiles)
			startActivityForResult(intent, ACTIVITY_CREATE_PROFILE);
		else
			startActivityForResult(intent, ACTIVITY_EDIT_PROFILE);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		Bundle extras = data.getExtras();

		switch (requestCode) {
		case ACTIVITY_CREATE_PROFILE:
			if (extras.getBoolean("CreatedProfile")) {
				mNumProfiles = mSettings.getInt("NumProfiles", 0);
				dispProfileList();
			}
			break;
		case ACTIVITY_EDIT_PROFILE:
			if (extras.getBoolean("EditedProfile"))
				dispProfileList();
			break;
		}
	}

	/**
	 * Function to delete a profile
	 * 
	 * @param profileIndex
	 */
	private void deleteProfile(int profileIndex) {
		// Delete this profile
		SharedPreferences.Editor editor = mSettings.edit();
		--mNumProfiles;
		for (int i = profileIndex; i < mNumProfiles; ++i) {
			editor.putString("Profile" + i + "Name", mSettings.getString(
					"Profile" + (i + 1) + "Name", "PhoneCard"));
			editor.putBoolean("Profile" + i + "Active", mSettings.getBoolean(
					"Profile" + (i + 1) + "Active", false));

			// Need to copy other fields as well

		}
		editor.putInt("NumProfiles", mNumProfiles);
		editor.commit();
		dispProfileList();
	}

	/**
	 * Create the ListAdapter that will contain all the profiles
	 */
	private void dispProfileList() {
		ProfileListAdapter adapter = new ProfileListAdapter(this);

		for (int i = 0; i < mNumProfiles; ++i) {
			adapter.addItem(mSettings.getString("Profile" + i + "Name",
					"PhoneCard"), mSettings.getBoolean(
					"Profile" + i + "Active", false));
		}

		setListAdapter(adapter);
	}

}
